summaryrefslogtreecommitdiff
path: root/app/[lng]/partners/pq_new/[id]/page.tsx
blob: 5a8313cc764c58a412a6eeb5f4cbd4bcea4a4668 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import { Metadata } from "next";
import Link from "next/link";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { Button } from "@/components/ui/button";
import { ArrowLeft, LogIn } from "lucide-react";
import { Shell } from "@/components/shell";
import { getPQById, getPQDataByVendorId } from "@/lib/pq/service";
import { unstable_noStore as noStore } from 'next/cache';
import { Alert, AlertDescription } from "@/components/ui/alert";
import { PQInputTabs } from "@/components/pq-input/pq-input-tabs";

export const metadata: Metadata = {
  title: "사전 평가 (PQ) 작성",
  description: "사전 평가 항목을 작성합니다.",
};

// 페이지가 기본적으로 동적임을 나타냄
export const dynamic = "force-dynamic";

interface PQEditPageProps {
  params: Promise<{ id: string }>;
}

export default async function PQEditPage(props: PQEditPageProps) {
  // 캐시 비활성화
  noStore();

  const params = await props.params;
  const pqSubmissionId = parseInt(params.id, 10);

  // 인증 확인
  const session = await getServerSession(authOptions);

  // 로그인 확인
  if (!session || !session.user) {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              사전 평가 (PQ) 작성
            </h2>
          </div>
        </div>

        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">로그인이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              사전 평가를 작성하려면 먼저 로그인하세요.
            </p>
            <Button size="lg" asChild>
              <Link href={`/partners?callbackUrl=/partners/pq/${pqSubmissionId}`}>
                <LogIn className="mr-2 h-4 w-4" />
                로그인하기
              </Link>
            </Button>
          </div>
        </div>
      </Shell>
    );
  }

  // 세션에서 vendorId 가져오기
  const vendorId = session.user.companyId;

  // 벤더 권한 확인
  if (session.user.domain !== "partners" || !vendorId) {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              접근 권한 없음
            </h2>
          </div>
        </div>
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">벤더 계정이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              벤더 계정으로 로그인해주세요.
            </p>
          </div>
        </div>
      </Shell>
    );
  }

  const idAsNumber = Number(vendorId);

  try {
    // PQ Submission 정보 조회 (vendorPQSubmissions 테이블에서)
    const pqSubmission = await getPQById(pqSubmissionId, idAsNumber);

    // 이 PQ가 현재 로그인한 벤더의 것인지 확인
    if (pqSubmission.vendorId !== idAsNumber) {
      throw new Error("Access denied - This PQ belongs to another vendor");
    }

    // PQ 데이터 조회 (pqCriterias와 답변)
    const pqData = await getPQDataByVendorId(idAsNumber, pqSubmission.projectId || undefined);

    // 상태에 따른 읽기 전용 모드 결정
    const isReadOnly = [ "APPROVED"].includes(pqSubmission.status);
    const statusText = pqSubmission.status === "SUBMITTED" ? "제출됨" :
      pqSubmission.status === "APPROVED" ? "승인됨" :
        pqSubmission.status === "REJECTED" ? "거부됨" : "작성 중";

    const pageTitle = pqSubmission.type === "PROJECT"
      ? `프로젝트 PQ - ${pqSubmission.projectName || pqSubmission.projectCode}`
      : pqSubmission.type === "NON_INSPECTION"
      ? "미실사 PQ"
      : "일반 PQ";

    // 프로젝트 정보 (프로젝트 PQ인 경우)
    const projectPQ = pqSubmission.projectId ? {
      id: pqSubmission.projectId,
      projectId: pqSubmission.projectId,
      projectCode: pqSubmission.projectCode || '',
      projectName: pqSubmission.projectName || '',
      status: pqSubmission.status,
      submittedAt: pqSubmission.submittedAt,
    } : null;

    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="outline" size="sm" asChild>
              <Link href="/partners/pq_new">
                <ArrowLeft className="w-4 h-4 mr-2" />
                목록으로
              </Link>
            </Button>
            <div>
              <h2 className="text-2xl font-bold tracking-tight">
                {pageTitle}
              </h2>
              <p className="text-muted-foreground">
                상태: {statusText}
                {pqSubmission.status === "REJECTED" && pqSubmission.rejectReason && (
                  <span className="text-destructive ml-2">
                    (거부 사유: {pqSubmission.rejectReason})
                  </span>
                )}
              </p>
            </div>
          </div>
        </div>

        {/* 읽기 전용 모드 알림 */}
        {/* {isReadOnly && (
          <Alert>
            <AlertDescription>
              이 PQ는 현재 제출된 상태입니다. SHI 코멘트를 확인 후 재제출이 가능합니다.
            </AlertDescription>
          </Alert>
        )} */}

        {/* PQ 입력 컴포넌트 */}
          <PQInputTabs
            data={pqData}
            vendorId={idAsNumber}
            projectId={pqSubmission.projectId || undefined}
            projectData={projectPQ}
            isReadOnly={isReadOnly}
            currentPQ={{  // 현재 PQ Submission 정보 전달
              id: pqSubmission.id,
              status: pqSubmission.status,
              type: pqSubmission.type
            }}
          />
      </Shell>
    );
  } catch (error) {
    console.error("Error loading PQ:", error);

    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              오류 발생
            </h2>
          </div>
        </div>
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">PQ를 불러올 수 없습니다</h3>
            <p className="mb-6 text-muted-foreground">
              요청하신 PQ를 찾을 수 없거나 접근 권한이 없습니다.
            </p>
            <Button asChild>
              <Link href="/partners/pq">
                <ArrowLeft className="mr-2 h-4 w-4" />
                목록으로 돌아가기
              </Link>
            </Button>
          </div>
        </div>
      </Shell>
    );
  }
}